/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.querydsl;

import com.google.common.collect.ImmutableList;
import com.querydsl.core.types.Path;
import com.querydsl.sql.RelationalPath;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
public class IndexBuilder {

    private final RelationalPath<?> entity;
    private final String indexName;
    private final List<Index> indexs;
    private final Map<Path<?>, Boolean> columnMap;
    private boolean unique;

    public IndexBuilder(RelationalPath<?> entity, String indexName, List<Index> indexs) {
        this.entity = entity;
        this.indexName = indexName;
        this.indexs = indexs;
        this.columnMap = new LinkedHashMap<>();
    }

    public IndexBuilder unique() {
        this.unique = true;
        return this;
    }

    public IndexBuilder column(Path<?> column) {
        return column(column, false);
    }

    public IndexBuilder column(Path<?> column, boolean desc) {
        columnMap.put(column, desc);
        return this;
    }

    public final Index build() {
        List<Index.IndexPath> columns = new ArrayList<>();
        for (Map.Entry<Path<?>, Boolean> entry : columnMap.entrySet()) {
            Path<?> path = entry.getKey();
            Boolean desc = entry.getValue();
            columns.add(new Index.IndexPath(path, desc));
        }
        Index index = new Index(entity, indexName, unique, ImmutableList.copyOf(columns));
        indexs.add(index);
        return index;
    }
}
